package com.app.micaihu.view.main.game.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.ArrayMap;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.volley.VolleyError;
import com.app.config.LoadViewConfig;
import com.app.micaihu.R;
import com.app.micaihu.app.AppApplication;
import com.app.micaihu.base.BaseListFragment;
import com.app.micaihu.base.bean.DataBean;
import com.app.micaihu.bean.game.GameCenterEntity;
import com.app.micaihu.bean.game.GameCenterList;
import com.app.micaihu.configure.Config;
import com.app.micaihu.configure.TypeConstant;
import com.app.micaihu.configure.URIContant;
import com.app.micaihu.configure.UmEventId;
import com.app.micaihu.listener.HttpListener;
import com.app.micaihu.manager.UserInforManager;
import com.app.micaihu.utils.MobclickAgentUtils;
import com.app.micaihu.view.main.MainActivity;
import com.app.micaihu.view.main.game.GameClassListActivity;
import com.app.micaihu.view.main.game.GameDetailActivity;
import com.app.micaihu.view.main.game.GameRaidersNewsActivity;
import com.app.micaihu.view.main.game.adapter.GameCenterAdapter;
import com.app.micaihu.view.main.game.adapter.GameListHeaderAdapter;
import com.app.utils.pulltorefresh.PullToRefreshBase;
import com.app.utils.util.StringUtils;
import com.baidu.mobstat.StatService;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.CollectionUtils;
import com.blankj.utilcode.util.LogUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.gson.reflect.TypeToken;
import com.youth.banner.Banner;
import com.youth.banner.adapter.BannerImageAdapter;
import com.youth.banner.holder.BannerImageHolder;
import com.youth.banner.indicator.RectangleIndicator;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 游戏中心Fragment
 * Created by linkai on 2017/3/13.
 */
public class GameCenterFragment extends BaseListFragment<GameCenterEntity> {

    private int mMark;
    int rankIndex = -1;//排行榜的位置
    private GameCenterEntity mGameRanking;

    //操作监听
    private MainActivity.OnRefreshingListener mOnRefreshingListener;

    //已经加载过的新闻 （用于新闻去重）
    private ArrayMap<String, String> listHasp = new ArrayMap<>();

    private Banner banner;
    private RecyclerView rvGame;
    private GameListHeaderAdapter gameListHeaderAdapter;

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    protected void changeView() {
        mPageName = "GameCenterFragment";

        ListView refreshableView = mListView.getRefreshableView();
        View view = LayoutInflater.from(getContext()).inflate(R.layout.game_list_header, null, false);
        banner = view.findViewById(R.id.banner);
        rvGame = view.findViewById(R.id.rvGame);

        gameListHeaderAdapter = new GameListHeaderAdapter();
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 4);
        rvGame.setLayoutManager(gridLayoutManager);
        rvGame.setAdapter(gameListHeaderAdapter);
        refreshableView.addHeaderView(view);

        gameListHeaderAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                GameCenterList.ClassList item = gameListHeaderAdapter.getItem(position);
                if (item == null) return;
                Intent intent = new Intent(getContext(), GameClassListActivity.class);
                Bundle bundle = new Bundle();
                bundle.putInt(Config.Extra.type, item.type);
                bundle.putString(Config.Extra.title, item.name);
                intent.putExtras(bundle);
                ActivityUtils.startActivity(intent);
            }
        });
        banner.setIndicator(new RectangleIndicator(getContext()));
    }

    @Override
    protected void changeData(final boolean isRefresh) {

        HashMap<String, String> paramMap = new HashMap<>();
        paramMap.put("page", dataPage + "");
        paramMap.put("mark", mMark + "");

        HttpListener<DataBean<GameCenterList>> blackListListener = new HttpListener<DataBean<GameCenterList>>() {

            @Override
            public void onStart() {
                super.onStart();
                setLoadView(LOADING, null);
                if (isRefresh && mMark == 1 && mOnRefreshingListener != null) {
                    //说明是手指下拉刷新
                    mOnRefreshingListener.onDataRefreshingStart();
                }
            }

            @Override
            public void onError(VolleyError error) {
                if (isRefresh && mMark == 1 && mOnRefreshingListener != null) {
                    mOnRefreshingListener.onDataRefreshingEnd();
                }
                setLoadView(NO_NET, AppApplication.getInstance().getString(R.string.neterror_click));
            }

            @Override
            public void onSuccess(DataBean<GameCenterList> response) {
                if (response.noErrorData()) {
                    GameCenterList data = response.getData();
                    if (data == null) return;
                    List<GameCenterList.ClassList> classList = data.getClassList();
                    if (CollectionUtils.isEmpty(classList)) {
                        rvGame.setVisibility(View.GONE);
                    } else {
                        rvGame.setVisibility(View.VISIBLE);
                        gameListHeaderAdapter.setNewInstance(classList);
                    }

                    List<GameCenterList.Banner> gameBannerList = data.getGameBannerList();
                    if (CollectionUtils.isEmpty(gameBannerList)) {
                        banner.setVisibility(View.GONE);
                    } else {
                        banner.setVisibility(View.VISIBLE);
                        banner.setAdapter(new BannerImageAdapter<GameCenterList.Banner>(gameBannerList) {
                            @Override
                            public void onBindView(BannerImageHolder holder, GameCenterList.Banner data, int position, int size) {
                                //图片加载自己实现
                                Glide.with(holder.itemView).load(data.thumb).into(holder.imageView);
                                holder.itemView.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        /**
                                         * type:
                                         * 1：游戏详情
                                         * 2:游戏分类
                                         * 3:h5
                                         * 4.游戏攻略
                                         * gameId:游戏ID
                                         * classType：游戏分类ID
                                         * url：h5地址
                                         */
                                        if (data.type == 1) {
                                            Intent intent = new Intent();
                                            intent.putExtra(Config.Extra.PARAMETER1, data.gameId);
                                            intent.setClass(activity, GameDetailActivity.class);
                                            startActivity(intent);
                                        } else if (data.type == 2) {
                                            Intent intent = new Intent(getContext(), GameClassListActivity.class);
                                            Bundle bundle = new Bundle();
                                            bundle.putInt(Config.Extra.type, data.classType);
                                            bundle.putString(Config.Extra.title, data.title);
                                            intent.putExtras(bundle);
                                            ActivityUtils.startActivity(intent);
                                        } else if (data.type == 3) {
                                            UserInforManager.getInstance().toWebActivity(getActivity(), "", data.url);
                                        } else if (data.type == 4) {
                                            Intent intent = new Intent();
                                            intent.putExtra(Config.Extra.PARAMETER2, data.gameId);
                                            intent.putExtra(Config.Extra.PARAMETER1, data.articleId);
                                            intent.setClass(activity, GameRaidersNewsActivity.class);
                                            startActivity(intent);
                                        }
                                    }
                                });
                            }
                        });
                    }

                    List<GameCenterEntity> gamelist = data.getGameList();
                    if (gamelist != null && gamelist.size() > 0) {
                        if (dataList == null) {
                            dataList = new ArrayList<>();
                        }
                        //数据去重
                        dataRevisited(gamelist, response.getData().getRandPosition());
                        if (gamelist.isEmpty()) {
                            //如果全部被去重则不做操作 直接显示刷新成功
                            setLoadView(LOADSUCES, null);
                            return;
                        }

                        if (isRefresh) {
                            if (mMark == 0) {
                                //清空数据
                                dataList.clear();
                                dataList.addAll(gamelist);
                            } else {
                                if (rankIndex > -1 && dataList != null && rankIndex < dataList.size()) {
                                    //如果当前已经有排行榜了则移除排行榜
                                    dataList.remove(rankIndex);
                                }
                                List<String> position = response.getData().getRandPosition();
                                if (position == null || position.isEmpty()) {
                                    dataList.addAll(0, gamelist);
                                } else if (!gamelist.isEmpty()) {
                                    for (int i = 0; i < position.size(); i++) {
                                        int index = StringUtils.toInt(position.get(i), -1) - 1;
                                        if (i < gamelist.size()) {
                                            if (index >= 0 && index < dataList.size()) {
                                                dataList.set(index, gamelist.get(i));
                                            }
                                        }
                                    }
                                }
                            }

                            GameCenterEntity gameRanking = flushRankData(response);
                            int index;
                            //根据索引,将排行榜插入到list 中
                            if (gameRanking != null) {
                                mGameRanking = gameRanking;
                                if (response.getData().getRankListPosition() >= dataList.size()) {
                                    index = dataList.size() - 1;
                                } else if (response.getData().getRankListPosition() < 0) {
                                    index = 0;
                                } else {
                                    index = response.getData().getRankListPosition();
                                }
                                if (index >= 0 && index < dataList.size()) {
                                    rankIndex = index;
                                }
                            }
                            if (rankIndex > -1 && mGameRanking != null) {
                                //添加排行榜
                                dataList.add(rankIndex, mGameRanking);
                            }
                        } else {
                            dataList.addAll(gamelist);
                        }

                        if (mAdapter == null) {
                            mAdapter = new GameCenterAdapter(dataList, activity);
                            mListView.setAdapter(mAdapter);
                        } else {
                            mAdapter.notifyDataSetChanged();
                        }
                        setLoadView(LOADSUCES, null);
                    } else {
                        //设置空数据页面展示
                        setLoadView(DATAEMPTY, TypeConstant.EMPTYVIEW_DEFAULT, "暂无游戏");
                    }
                } else {
                    setLoadView(DATAERROR, response.getNnderstoodMsg());
                }
            }
        };

        addPostCacheRequest(URIContant.GAME_CENTER_LIST, new TypeToken<DataBean<GameCenterList>>() {
        }.getType(), paramMap, blackListListener);
    }

    /**
     * 数据去重
     *
     * @param list
     * @param position
     */
    private void dataRevisited(List<GameCenterEntity> list, List<String> position) {
        for (int i = 0; i < list.size(); i++) {
            if (i >= list.size()) {
                break;
            }
            GameCenterEntity gameCenterEntity = list.get(i);
            if (gameCenterEntity == null) {
                continue;
            }
            //开始去重计算
            if (listHasp.get(gameCenterEntity.getArticleId()) == null) {
                listHasp.put(gameCenterEntity.getArticleId(), gameCenterEntity.getArticleId());
            } else {
                list.remove(i);
                if (position != null && i < position.size()) {
                    position.remove(i);
                }
                i--;
            }
        }
    }


    /**
     * 刷新 排行榜
     *
     * @param response
     */
    private GameCenterEntity flushRankData(DataBean<GameCenterList> response) {
        GameCenterEntity gameRanking = null;
        //获取排行榜数据
        List<GameCenterEntity> gameCenterEntityList = response.getData().getRankList();
        if (gameCenterEntityList != null && gameCenterEntityList.size() > 0) {
            gameRanking = new GameCenterEntity();
            gameRanking.setIsRankList("0");
        }


        return gameRanking;
    }

    /**
     * 重载的Loadview EmptyView的方法
     *
     * @param code  DATAEMPTY
     * @param resId 对应的图片
     * @param msg   暂时最多传两个String，第一个对应小字体，第二个对应加粗字体
     */
    protected void setLoadView(int code, final int resId, final String... msg) {
        switch (code) {
            case DATAEMPTY:
                mListView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (dataList == null || dataList.size() == 0) {
                            mLoadView.showEmptyPage(resId, msg);
                        }
                        if (mListView != null && mListView.isRefreshing()) {
                            mListView.onRefreshComplete();
                        }
                    }
                }, 800);

                break;
        }

    }

    /**
     * LoadViewd 方法
     *
     * @param code 传入对应的值
     * @param msg  提示的的文字
     */
    protected void setLoadView(int code, CharSequence msg) {

        switch (code) {
            case NO_NET://网络错误
            case DATAERROR://数据错误
                if (dataList == null || dataList.size() == 0) {
                    mLoadView.showErrorPage(msg);
                }
                if (mListView != null) {
                    mListView.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mListView.onRefreshComplete();
                            //更改 底部导航栏
                            if (mOnRefreshingListener != null) {
                                mOnRefreshingListener.onDataRefreshingEnd();
                            }
                        }
                    }, 800);
                }
                break;
            case LOADING://加载中
                if (dataList == null || dataList.size() == 0) {
                    mLoadView.showLoadPage(msg);
                }
                break;
            case LOADSUCES://加载成功
                if (dataList != null && dataList.size() > 0) {
                    mLoadView.showSuccess();
                } else {
                    mLoadView.showEmptyPage(LoadViewConfig.EMPTY_DEFAULT, "");
                }
                if (mListView != null) {
                    mListView.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mListView.onRefreshComplete();
                            //更改 底部导航栏
                            if (mOnRefreshingListener != null) {
                                mOnRefreshingListener.onDataRefreshingEnd();
                            }
                        }
                    }, 800);
                }
                break;
        }
        if (msg != null && !"".equals(msg)) {
            notify_view_text.setText(msg);
            notify_view_text.setVisibility(View.VISIBLE);
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    notify_view_text.setVisibility(View.GONE);
                }
            }, 2000);
        }
    }

    @Override
    public void onItemClick(AdapterView parent, View view, int position, long id) {
        position = position - mListView.getRefreshableView().getHeaderViewsCount();
        GameCenterEntity news = dataList.get(position);
        if (news == null || activity == null) {
            return;
        }
        Intent intent = new Intent();
        intent.putExtra(Config.Extra.PARAMETER1, news.getArticleId());
        intent.setClass(activity, GameDetailActivity.class);
        startActivity(intent);
        MobclickAgentUtils.event(UmEventId.game_click, UmEventId.INSTANCE.getList());
        StatService.onEvent(AppApplication.getInstance(), "067", "游戏", 1);
    }


    @Override
    public void onResume() {
        super.onResume();
//        if (DownloadUtils.DOWNLOADED != 0) {
//            if (mAdapter != null) {
//                mAdapter.notifyDataSetChanged();
//            }
//        }
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            notifyDown();
        }
    }

    public void notifyDown() {
//        if (DownloadUtils.DOWNLOADED != 0) {
//            if (mAdapter != null) {
//                mAdapter.notifyDataSetChanged();
//            }
//        }
    }


    public void setOnRefreshingListener(MainActivity.OnRefreshingListener mOnRefreshingListener) {

        this.mOnRefreshingListener = mOnRefreshingListener;
    }

    /**
     * 重写下拉刷新
     *
     * @param refreshView
     */
    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        this.mMark = 1;
        super.onPullDownToRefresh(refreshView);
        StatService.onEvent(activity, "066", "游戏列表下拉", 1);//统计事件的点击次数
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        this.mMark = 0;
        super.onPullUpToRefresh(refreshView);
        StatService.onEvent(activity, "066", "游戏列表上拉", 1);//统计事件的点击次数
    }
}
